package net.zjitc.intercepter;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.zjitc.utils.APIResponse;
import net.zjitc.utils.JwtUtil;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AdminInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("jwt");
//        Object admin = request.getSession().getAttribute("admin");
        //验证token是否存在
        // 检查JWT是否存在

        if (token == null || token.isEmpty()) {
            sendErrorResponse(response, "JWT token is missing", HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        // 验证JWT
        if (!JwtUtil.validateToken(token)) {
            sendErrorResponse(response, "Invalid or expired JWT token", HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        // 如果JWT有效，可以将解析出的用户名或其他信息存储在请求中供后续使用
        String username = JwtUtil.getUsernameFromToken(token);
        request.setAttribute("username", username);

        return true;
    }
    private void sendErrorResponse(HttpServletResponse response, String message, int statusCode) throws IOException {
        response.setStatus(statusCode);
        response.setContentType("application/json");
        ObjectMapper objectMapper = new ObjectMapper();
        APIResponse<String> apiResponse = new APIResponse<>();
        apiResponse.failed(message, null);
        objectMapper.writeValue(response.getWriter(), apiResponse);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
